package com.wangbl.infomanager;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tangye.android.http.Request.ResponseListener;
import com.wangbl.infomanager.bean.MainInfoBean;
import com.wangbl.infomanager.http.Http;
import com.wangbl.infomanager.http.Response;
import com.wangbl.infomanager.utils.Logger;
import com.wangbl.infomanager.view.XListView;
import com.wangbl.infomanager.view.XListView.OnXListViewListener;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class InfoMainActivity extends BaseActivity implements OnXListViewListener, OnClickListener, OnItemClickListener {

	protected static final String TAG = "InfoMainActivity";

	public static final int USER_INFO = 20;
	public static final int CLOSE_ACTIVTY = 21;

	private XListView listView;
	private List<MainInfoBean> infos;
	private InfoMainAdapter adapter;
	private Http http;
	private MyViewPagerAdapter pagerAdapter;
	private View viewPagerLayout;

	private ViewPager viewPager;
	private int currPoint;
	private LinearLayout pagePoint;
	private List<String> titleImages = new ArrayList<String>();

	private SharedPreferences sp;
	private SharedPreferences sp_push_msg_state;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_info_main);

		super.onCreate(savedInstanceState);

		sp_push_msg_state = getSharedPreferences("push_msg_state", Context.MODE_PRIVATE);

		listView = (XListView) findViewById(R.id.lv_info_main_content);
		adapter = new InfoMainAdapter();
		infos = new ArrayList<MainInfoBean>();

		viewPagerLayout = View.inflate(InfoMainActivity.this, R.layout.item_listview_info_main_viewpager, null);
		viewPager = (ViewPager) viewPagerLayout.findViewById(R.id.viewpager_info_main);
		pagePoint = (LinearLayout) viewPagerLayout.findViewById(R.id.viewpager_points_info_main);
		pagerAdapter = new MyViewPagerAdapter();
		viewPager.setAdapter(pagerAdapter);

		title_text.setText("人大信管");
		title_back.setVisibility(View.GONE);
		title_menu.setVisibility(View.VISIBLE);

		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(this);

		title_menu.setOnClickListener(this);
		title_user.setOnClickListener(this);
		doRequest(true);
	}

	@Override
	protected void onStart() {

		super.onStart();

		int readCount = sp_push_msg_state.getInt("readCount", 0);
		if (readCount > 0) {
			title_user.setImageResource(R.drawable.title_user_icon2);
		} else {
			title_user.setImageResource(R.drawable.title_user_icon);
		}

	}

	private void initPagerPonint() {
		pagePoint.removeAllViews();
		for (int i = 0; i < titleImages.size(); i++) {
			View view = View.inflate(this, R.layout.item_info_main_pointer, null);
			ImageView image = (ImageView) view.findViewById(R.id.item_pointer_image);
			if (i == currPoint) {
				image.setImageResource(R.drawable.info_main_pointer_checked);
			} else {
				image.setImageResource(R.drawable.info_main_pointer_unchecked);
			}
			pagePoint.addView(view);
		}

		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				ImageView image1 = (ImageView) pagePoint.getChildAt(currPoint).findViewById(R.id.item_pointer_image);
				image1.setImageResource(R.drawable.info_main_pointer_unchecked);
				ImageView image2 = (ImageView) pagePoint.getChildAt(position).findViewById(R.id.item_pointer_image);
				image2.setImageResource(R.drawable.info_main_pointer_checked);
				currPoint = position;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

	}

	// http://irmsma.ruc.edu.cn/rucjson/index_content.php?id
	private void doRequest(boolean flag) {
		Logger.i(TAG, "doRequest");
		if(flag){
			pd.show();
		}
		imageDoRequest();
		Http http = new Http("/rucjson/index.php", true);
		http.setDebug(Http.isDebug);
		http.asyncRequest(new ResponseListener<Response>() {

			@Override
			public void onResp(int arg0, Response resp, Object... arg2) {
//				Logger.i(TAG, "json:"+resp.json);
				infos = parser(resp.json);
				if (infos != null) {
					adapter.notifyDataSetChanged();
					doRequestTitle();
				} else {
					toast("请求数据出错...");
					pd.dismiss();
				}
			}

			@Override
			public void onErr(int arg0, String arg1, int arg2, Object... arg3) {
				pd.dismiss();
				toast(arg1);
			}

		});

	}

	private void imageDoRequest() {
		Logger.i(TAG, "imageDoRequest");
		Http h = new Http("/rucjson/phoneimg.php", true);
		h.setDebug(Http.isDebug);
		h.asyncRequest(new ResponseListener<Response>() {

			@Override
			public void onResp(int arg0, Response arg1, Object... arg2) {
//				Logger.i(TAG, "arg1.json" + arg1.json);
				titleImages = parserImagePath(arg1.json);
//				Logger.i(TAG, "titleImages:" + Arrays.toString(titleImages.toArray()));
				initPagerPonint();
				pagerAdapter.notifyDataSetChanged();
			}

			@Override
			public void onErr(int arg0, String arg1, int arg2, Object... arg3) {
				toast(arg1);
			}
		});
	}

	private List<String> parserImagePath(String json) {
		List<String> list = new ArrayList<String>();
		JSONObject obj;
		try {
			obj = new JSONObject(json);
			JSONArray titles = obj.getJSONArray("Title");
			for (int i = 0; i < titles.length(); i++) {
				JSONObject o = titles.getJSONObject(i);
				list.add("http://irmsma.ruc.edu.cn" + o.getString("imgpath"));
			}
			return list;
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return list;
	}

	private void doRequestTitle() {
		Logger.i(TAG, "doRequestTitle");
		if (infos == null) {
			toast("数据出错...");
			return;
		}
		for (int i = 0; i < infos.size(); i++) {
			MainInfoBean info = infos.get(i);
			http = new Http("/rucjson/index_content.php", true);
			http.setParam("id", info.getId());
			http.asyncRequest(i, new ResponseListener<Response>() {

				@Override
				public void onResp(int arg0, Response arg1, Object... arg2) {
					Logger.i(TAG, "arg1:"+arg1.json);
					MainInfoBean in = infos.get(arg0);
					parserTitle(arg1.json, in);
					adapter.notifyDataSetChanged();
					if (arg0 == infos.size() - 1) {
						pd.dismiss();
					}
					listView.stopRefresh();
				}

				@Override
				public void onErr(int arg0, String arg1, int arg2, Object... arg3) {
					pd.dismiss();
				}

			});
		}

	}

	private class MyViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return titleImages.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			if (object instanceof View) {
				View view = (View) object;
				view.setTag(null);
				container.removeView((View) object);
			}

		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view;
			view = View.inflate(InfoMainActivity.this, R.layout.item_viewpager_info_main, null);
			ImageView image = (ImageView) view.findViewById(R.id.iv_item_info_main);
//			Logger.i(TAG, "titleImages.get(position):" + titleImages.get(position));
			ImageLoader.getInstance().displayImage(titleImages.get(position), image);
			container.addView(view);

			return view;
		}

		@Override
		public boolean isViewFromObject(View view, Object obj) {
			return view == obj;
		}

	}

	private class InfoMainAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			return infos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			Holder holder;
			MainInfoBean info = infos.get(position);
			if (position == 0) {
				return viewPagerLayout;
			}
			if (convertView != null && convertView.getTag() instanceof Holder) {
				view = convertView;
				holder = (Holder) view.getTag();
			} else {
				view = View.inflate(InfoMainActivity.this, R.layout.item_listview_info_main, null);
				holder = new Holder();
				holder.tv_title = (TextView) view.findViewById(R.id.tv_item_info_main_title);
				holder.tv_type = (TextView) view.findViewById(R.id.tv_info_main_type);
				holder.tv_date = (TextView) view.findViewById(R.id.tv_info_main_date);
				view.setTag(holder);
			}

			holder.tv_title.setText(info.getTitle());
			holder.tv_type.setText(info.getName());
			holder.tv_date.setText(info.getDatetime());

			return view;
		}

	}

	class Holder {
		TextView tv_title;
		TextView tv_type;
		TextView tv_date;
	}

	private void parserTitle(String json, MainInfoBean info) {
		try {
			JSONObject obj = new JSONObject(json);
			JSONObject obj_col = obj.getJSONObject("column");
			JSONArray title = obj_col.getJSONArray("title");
			info.setTitle(title.getString(0));

//			JSONArray content = obj_col.getJSONArray("content");
//			info.setDeatilUrl(content.getString(0));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List<MainInfoBean> parser(String json) {
		List<MainInfoBean> infos;
		Gson gson = new Gson();
		Type type = new TypeToken<ArrayList<MainInfoBean>>() {
		}.getType();
		infos = gson.fromJson(json, type);
		infos.add(0, new MainInfoBean());
		return infos;
	}

	@Override
	public void onRefresh() {
		doRequest(false);
	}

	@Override
	public void onLoadMore() {
//		Logger.i(TAG, "onLoadMore");
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.iv_title_menu:
			Intent intent = new Intent(this, CatalogActivity.class);
			startActivity(intent);
			break;
		case R.id.iv_title_user:
			Intent i = new Intent(this, UserInfoActivity.class);
			startActivityForResult(i, USER_INFO);
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Logger.i(TAG, "position:"+position+"   "+infos.size());
		MainInfoBean info = infos.get(position-1);
		Logger.i(TAG, "id:"+info.getId());
		if (info.getId() == null) {
			toast("此条信息详情不存在...");
			return;
		}

		Intent intent = new Intent(this, InfoDetailActivity.class);
		intent.putExtra("url", "http://irmsma.ruc.edu.cn/dis.php?id="+info.getId());
		startActivity(intent);
	}

	@Override
	protected void interrupt() {
		if (http != null) {
			http.abort();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
//		Logger.i(TAG, requestCode + "   " + resultCode);
		if (requestCode == USER_INFO) {
			if (resultCode == CLOSE_ACTIVTY) {
				finish();
			}
		}
	}

}
